<?php
/**
 * 定时任务服务类
 *
 * @author liang<lang@vip.deyi.com>
 * @since   2015/8/26 11:47
 * @copyright  deyi.com
 */

namespace Apps\Common\Service;

use Apps\Weixin\Models\WxCron;
use Vendor\CronExpression\CronExpression;

/**
 * Class TaskCronService
 * @package Apps\Common\Service
 */
class TaskCronService extends WxCron
{
    /**
     *  添加单次异步定时任务
     *
     * @author liang<lang@vip.deyi.com>
     * @param $taskName
     * @param $taskData
     * @param $dateTime
     * @return bool|int
     */
    public function addTaskOnce($taskName, $taskData, $dateTime)
    {
        $arr = date_parse_from_format('Y-m-d H:i:s', $dateTime);

        $cron = $arr['minute'] . ' ' . $arr['hour'] . ' ' . $arr['day'] . ' ' . $arr['month'] . ' *';

        if ($this->insert($taskName, serialize($taskData), $cron, 1)) {
            return $this->getLastId();
        } else {
            return false;
        }
    }

    /**
     *  任务运行
     *
     * @author liang<lang@vip.deyi.com>
     */
    public function runTask()
    {
        static::$_logger->info('#TimerTask Begin#');
        $list = $this->getTaskList();

        if ($list !== false && !empty($list)) {
            foreach ($list as $v) {
                if (CronExpression::factory($v->cron)->isDue()) {
                    $taskData = @unserialize($v->taskdata);
                    TaskService::doAsyncTask($v->taskname, $taskData ? $taskData : []);
                    //如果只执行一次的就清理掉这个任务
                    if ($v->once == 1) {
                        $this->deleteById($v->id);
                    }
                }
            }
        }
        static::$_logger->info('#TimerTask End#');
    }
}
